#!/usr/bin/env python3
"""
MTX MCP Server

面向 mtx 软件（磁带库管理工具）的 MCP 服务器，提供对 mtx 相关命令行工具的封装。

MCP tools 列表：
1. mtx_loaderinfo - 获取磁带库加载器信息
   参数：device (str) - 设备路径
   返回：统一的 JSON 结构

2. mtx_version - 获取 mtx 版本信息
   参数：无
   返回：统一的 JSON 结构

3. mtx_operation - 执行 mtx 各种操作
   参数：device (str) - 设备路径, operation (str) - 操作类型, args (List[str]) - 操作参数
   返回：统一的 JSON 结构

4. mtx_scsieject - 执行 scsieject 操作
   参数：device (str) - 设备路径, operation (str) - 操作类型
   返回：统一的 JSON 结构

5. mtx_scsitape - 执行 scsitape 操作
   参数：device (str) - 设备路径, operation (str) - 操作类型, args (List[str]) - 操作参数
   返回：统一的 JSON 结构

6. mtx_tapeinfo - 获取磁带驱动器信息
   参数：device (str) - 设备路径
   返回：统一的 JSON 结构
"""

import subprocess
import shlex
from typing import List
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("MTX MCP Server")

@mcp.tool()
def mtx_loaderinfo(device: str, ctx: Context) -> dict:
    """
    获取磁带库加载器信息
    
    参数:
        device: 磁带库设备路径（如 /dev/sg0）
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"loaderinfo -f {shlex.quote(device)}"
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def mtx_version(ctx: Context) -> dict:
    """
    获取 mtx 版本信息
    
    参数:
        无
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = "mtx --version"
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=10
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def mtx_operation(device: str, operation: str, args: List[str] = None, ctx: Context = None) -> dict:
    """
    执行 mtx 各种操作
    
    参数:
        device: 磁带库设备路径（如 /dev/sg0）
        operation: 操作类型（noattach、inquiry、inventory、status、first、last、previous、next、unload、load、transfer）
        args: 操作参数列表（如对于 load 操作需要 [slot, drive]）
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    if args is None:
        args = []
    
    args_str = " ".join(shlex.quote(str(arg)) for arg in args)
    command = f"mtx -f {shlex.quote(device)} {operation} {args_str}".strip()
    
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def mtx_scsieject(device: str, operation: str, ctx: Context) -> dict:
    """
    执行 scsieject 操作
    
    参数:
        device: 磁带设备路径（如 /dev/st0）
        operation: 操作类型（load、start、lock、unlock）
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"scsieject -f {shlex.quote(device)} {operation}"
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def mtx_scsitape(device: str, operation: str, args: List[str] = None, ctx: Context = None) -> dict:
    """
    执行 scsitape 操作
    
    参数:
        device: 磁带设备路径（如 /dev/st0）
        operation: 操作类型（setblk、fsf、bsf、eod、rewind、mark、seek、write、read、eject）
        args: 操作参数列表
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    if args is None:
        args = []
    
    args_str = " ".join(shlex.quote(str(arg)) for arg in args)
    command = f"scsitape -f {shlex.quote(device)} {operation} {args_str}".strip()
    
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def mtx_tapeinfo(device: str, ctx: Context) -> dict:
    """
    获取磁带驱动器信息
    
    参数:
        device: 磁带设备路径（如 /dev/sg0）
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = f"tapeinfo -f {shlex.quote(device)}"
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=30
        )
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()